package com.das.mechanic_base.mvp.presenter.camera;

import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;

import androidx.loader.app.LoaderManager;
import androidx.loader.content.CursorLoader;
import androidx.loader.content.Loader;

import com.das.mechanic_base.base.X3BasePresenter;
import com.das.mechanic_base.mvp.contract.camera.CameraPhotoContract;
import com.das.mechanic_base.bean.camera.Folder;
import com.das.mechanic_base.bean.camera.ImageVideoBean;
import com.das.mechanic_base.utils.X3StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class X3CameraPhotoPresenter extends X3BasePresenter<CameraPhotoContract.View> implements CameraPhotoContract.Presenter {

    /**
     * 图片+视频数据
     */
    private List<ImageVideoBean> images = new ArrayList();

    /**
     * 图片+视频 文件夹数据
     */
    private List<Folder> mResultFolder = new ArrayList<>();

    private boolean hasImageFolder = false;

    private boolean hasVideoFolder = false;

    @Override
    public void loadMediaList() {
        images.clear();
        if(mView.isAlbum() == 1 && mView.isShowVideo() == 1){//相册  只显示视频
            mView.getSupportManager().initLoader(1, null, videoLoader);
        }else {
            mView.getSupportManager().initLoader(0, null, imageLoader);
        }

    }

    private LoaderManager.LoaderCallbacks<Cursor> imageLoader = new LoaderManager.LoaderCallbacks<Cursor>() {

        private final String[] IMAGE_PROJECTION = {
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Thumbnails._ID};

        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            if(id == 0) {
                CursorLoader cursorLoader = new CursorLoader(mView.getViewContext(),
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION,
                        null, null,  MediaStore.Images.Media.DATE_MODIFIED);
                return cursorLoader;
            }

            return null;
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            if (data != null) {
                int count = data.getCount();
                images.clear();
                if (count > 0) {
                    data.moveToFirst();
                    String[] currentPro = IMAGE_PROJECTION;

                    do{
                        String path = data.getString(data.getColumnIndexOrThrow(currentPro[0]));
                        long addTime = data.getLong(data.getColumnIndexOrThrow(currentPro[1]));

                        File file = new File(path);
                        if (file.exists()) {
                            ImageVideoBean image = new ImageVideoBean(path, addTime,0);

                            images.add(image);

//                            if(StringUtils.isListEmpty(images)){
//                                images.add(image);
//                            }else {
//                                for (int i = 0; i < images.size(); i++) {
//                                    images.add(image);
////                                    if (!images.get(i).path.equals(image.path)) {
////                                        images.add(image);
////                                    }
//                                }
//                            }

                            if(!hasImageFolder) {
                                // 获取文件夹名称
                                File imageFile = new File(path);
                                File folderFile = imageFile.getParentFile();
                                Folder folder = new Folder();
                                folder.name = folderFile.getName();
                                folder.path = folderFile.getAbsolutePath();
                                folder.cover = image;
                                if (!mResultFolder.contains(folder)) {
                                    List<ImageVideoBean> imageList = new ArrayList();
                                    imageList.add(image);
                                    folder.images = imageList;
                                    mResultFolder.add(folder);
                                } else {
                                    // 更新
                                    Folder f = mResultFolder.get(mResultFolder.indexOf(folder));
                                    f.images.add(image);
                                }
                            }
                        }

                    }while(data.moveToNext());
                    hasImageFolder = true;
                }

                if (mView.isAlbum() == 1 || mView.isAlbum() == 3 || mView.isAlbum() == 4) {
                    comparatorImages();
                }else {
                    mView.getSupportManager().initLoader(1, null, videoLoader);
                }
                mView.getSupportManager().destroyLoader(0);
            }
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {

        }
    };

    private LoaderManager.LoaderCallbacks<Cursor> videoLoader = new LoaderManager.LoaderCallbacks<Cursor>() {

        private final String[] VIDEO_PROJECTION = {
                MediaStore.Video.Media.DATA,
                MediaStore.Video.Media.DATE_ADDED,
                MediaStore.Video.Thumbnails._ID,
                MediaStore.Video.Media.DURATION
        };

        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            if (id == 1) {
                CursorLoader cursorLoader = new CursorLoader(mView.getViewContext(),
                        MediaStore.Video.Media.EXTERNAL_CONTENT_URI, VIDEO_PROJECTION,
                        null, null, VIDEO_PROJECTION[1]);

                return cursorLoader;
            }
            return null;
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            if (data != null) {
                int count = data.getCount();
                if (count > 0) {
                    data.moveToFirst();
                    String[] currentPro = VIDEO_PROJECTION;
                    do{
                        String path = data.getString(data.getColumnIndexOrThrow(currentPro[0]));
                        long addTime = data.getLong(data.getColumnIndexOrThrow(currentPro[1]));
                        int duration = data.getInt(data.getColumnIndexOrThrow(currentPro[3])) / 1000;

                        File file = new File(path);

                        if (file.exists()) {
                            ImageVideoBean image = new ImageVideoBean(path, addTime,0);
                            if (duration > 1 && duration <= 30) {
                                image.setTime(duration);
                                images.add(image);

                            }
                            if(!hasVideoFolder) {
                                // 获取文件夹名称
                                File imageFile = new File(path);
                                File folderFile = imageFile.getParentFile();
                                Folder folder = new Folder();
                                folder.name = folderFile.getName();
                                folder.path = folderFile.getAbsolutePath();
                                folder.cover = image;
                                if (!mResultFolder.contains(folder)) {
                                    List<ImageVideoBean> imageList = new ArrayList();
                                    imageList.add(image);
                                    folder.images = imageList;
                                    mResultFolder.add(folder);
                                } else {
                                    // 更新
                                    Folder f = mResultFolder.get(mResultFolder.indexOf(folder));
                                    f.images.add(image);
                                }
                            }
                        }
                    }while(data.moveToNext());
                    hasVideoFolder = true;
                    //images 视频list
                }
                comparatorImages();
            }
            mView.getSupportManager().destroyLoader(1);
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {

        }
    };

    /**
     * 对图片或者视频进行时间重排序
     */
    private void comparatorImages() {
        Comparator<ImageVideoBean> imageComparatore = (s1, s2) -> {
            /**
             * 针对照片和视频 按照添加时间排序
             */
            if (s2.addTime <= 0){
                if (s1.addTime<= 0){
                    return 0;
                }
                return 1;
            }
            if (s1.addTime <= 0){
                return -1;
            }
            return (int) (s2.addTime - s1.addTime);
        };
        Collections.sort(images,imageComparatore);
        mView.showMediaList(images);

        for (Folder mFolder : mResultFolder) {
            List<ImageVideoBean> folderImages = mFolder.images;
            if (!X3StringUtils.isListEmpty(folderImages)) {
                Collections.sort(folderImages,imageComparatore);
                mFolder.images = folderImages;
            }
        }

        mView.showFolderList(mResultFolder);
    }
}
